package service

import (
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
	"anban/models"
)

// 获取微信被动消息信息
func GetWechatReplyInfo(p map[string]interface{}) *models.WechatReply {
	o := orm.NewOrm()
	wechatReply := &models.WechatReply{}
	qs := o.QueryTable("WechatReply")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["keyword"]; ok {
		qs = qs.Filter("keyword", p["keyword"])
	}
	if _, ok := p["vagueKeyword"]; ok {
		qs = qs.Filter("keyword__contains", p["vagueKeyword"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	qs.One(wechatReply)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if wechatReply.Id > 0 {
			wechatReply.TypeShow = models.WechatReplyType[wechatReply.Type]
			wechatReply.StatusShow = models.WechatReplyStatus[wechatReply.Status]
		}
	}
	return wechatReply
}

// 添加微信被动消息
func AddWechatReply(input url.Values) (int64, error) {
	o := orm.NewOrm()
	wechatReply := &models.WechatReply{}
	if _, ok := input["type"]; ok {
		wechatReply.Type, _ = strconv.Atoi(input["type"][0])
	}
	if _, ok := input["keyword"]; ok {
		wechatReply.Keyword = input["keyword"][0]
	}
	if _, ok := input["text"]; ok {
		wechatReply.Text = input["text"][0]
	}
	if _, ok := input["media_id"]; ok {
		wechatReply.MediaId = input["media_id"][0]
	}
	if _, ok := input["media_url"]; ok {
		wechatReply.MediaUrl = input["media_url"][0]
	}
	if _, ok := input["local_url"]; ok {
		wechatReply.LocalUrl = input["local_url"][0]
	}
	if _, ok := input["status"]; ok {
		wechatReply.Status, _ = strconv.Atoi(input["status"][0])
	}
	return o.Insert(wechatReply)
}

// 修改微信被动消息信息
func EditWechatReply(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("WechatReply").Filter("id", input["id"][0]).Update(p)
}

// 获取微信被动消息列表
func GetWechatReplyList(p map[string]interface{}) (int64, []*models.WechatReply) {
	var wechatReplyList []*models.WechatReply
	o := orm.NewOrm()
	qs := o.QueryTable("WechatReply")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["keyword"]; ok {
		qs = qs.Filter("keyword__contains", p["keyword"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&wechatReplyList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, wechatReply := range wechatReplyList {
			wechatReply.TypeShow = models.WechatReplyType[wechatReply.Type]
			wechatReply.StatusShow = models.WechatReplyStatus[wechatReply.Status]
		}
	}
	return totalCount, wechatReplyList
}
